<script>
import axios from "axios"; // 引入axios库用于发起HTTP请求

export default {
  name: "TopMenu", // 组件名称
  data() {
    return {
      activeIndex: "1", // 默认选中的菜单项索引
      dialogFormVisible: false, // 控制借阅信息弹窗的显示与隐藏
      dialogBookFormVisible: false, // 控制添加图书信息弹窗的显示与隐藏
      Form: { // 借阅信息表单的数据模型
        name: "",
        phone: "",
        bookName: "",
        borrowDate: null, // 借阅日期
        returnDate: null, // 归还日期
      },
      bookForm: { // 图书信息表单的数据模型
        bookName: "",
        author: "",
        quantity: 0, // 图书数量初始化为0
        isbn: "",
      },
      rules: { // 表单验证规则
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        bookName: [{ required: true, message: "请输入书名", trigger: "blur" }],
        borrowDate: [{ required: true, message: "请选择借阅日期", trigger: "blur" }],
      },
    };
  },
  methods: {
    handleSelect(key, keyPath) {
      console.log(key, keyPath); // 打印选中的菜单项
    },
    openAddDialog() {
      this.Form = { // 重置表单数据
        name: "",
        phone: "",
        bookName: "",
        borrowDate: null,
        returnDate: null,
      };
      this.dialogFormVisible = true; // 显示借阅信息弹窗
    },
    openAddBookDialog() {
      this.bookForm = { // 重置图书表单数据
        bookName: "",
        author: "",
        quantity: 0, // 初始化为0
        isbn: "",
      };
      this.dialogBookFormVisible = true; // 显示添加图书信息弹窗
    },
    // 用户添加方法
    async submitAdd() {
      // 验证借阅日期是否为空
      if (!this.Form.borrowDate) {
        this.$message.error("借阅日期不能为空！");
        return;
      }

      // 验证归还日期不能比借阅日期小
      if (this.Form.returnDate && new Date(this.Form.returnDate) < new Date(this.Form.borrowDate)) {
        this.$message.error("归还日期不能早于借阅日期！");
        return;
      }
      const formattedForm = { // 格式化表单数据
        ...this.Form,
        borrowDate: this.formatDate(this.Form.borrowDate), // 格式化借阅日期
        returnDate: this.Form.returnDate ? this.formatDate(this.Form.returnDate) : null, // 格式化归还日期
      };

      console.log(formattedForm); // 打印格式化后的表单数据

      try {
        const bookName = this.Form.bookName; // 获取书名
        const updateBookResponse = await axios.get(`http://localhost:8081/user/updateBook/${bookName}`); // 请求更新书籍信息
        if (updateBookResponse.data.code !== 1) {
          this.$message.error(updateBookResponse.data.message || "书籍数量不足"); // 提示错误信息
          return;
        }

        const response = await axios.post("http://localhost:8081/user/addUser", formattedForm); // 发起添加用户的请求

        if (response.data.code === 1) {
          this.$message.success(response.data.message || "添加用户成功！"); // 提示成功信息
          this.$emit('submitUserSuccess'); // 触发自定义事件
          this.dialogFormVisible = false; // 隐藏弹窗
        } else {
          this.$message.error(response.data.message || "添加用户失败！"); // 提示错误信息
        }
      } catch (error) {
        console.error("添加失败：", error); // 打印错误信息
        this.$message.error(error.response ? error.response.data.message : "添加失败"); // 提示错误信息
      }
    },
    async submitAddBook() {
      try {
        const response = await axios.post("http://localhost:8081/user/addBook", this.bookForm); // 发起添加图书的请求
        if (response.data.code === 1) {
          this.$message.success(response.data.message || "添加图书成功！"); // 提示成功信息
          this.dialogBookFormVisible = false; // 隐藏弹窗
        } else {
          this.$message.error(response.data.message || "添加图书失败！"); // 提示错误信息
        }
      } catch (error) {
        console.error("添加图书失败：", error); // 打印错误信息
        this.$message.error(error.response ? error.response.data.message : "添加图书失败"); // 提示错误信息
      }
    },
    formatDate(date) { // 日期格式化方法
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以+1
      const day = d.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`; // 返回格式化后的日期字符串
    },
  },
};
</script>

<template>
  <div id="TopMenu">
    <!-- 顶部菜单 -->
    <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
        background-color="#545c64"
        text-color="#fff"
        active-text-color="#ffd04b"
    >
      <el-menu-item index="3" disabled>借阅管理系统</el-menu-item>
      <el-menu-item index="1">信息处理</el-menu-item>
      <el-submenu index="2">
        <template #title>添加数据</template>
        <el-menu-item index="2-1" @click="openAddDialog">添加借阅信息</el-menu-item>
      </el-submenu>
    </el-menu>

    <!-- 添加借阅信息弹窗 -->
    <el-dialog
        title="添加借阅信息"
        :visible.sync="dialogFormVisible"
        width="500px"
        top="12vh"
    >
      <el-form :model="Form" :rules="rules" ref="Form">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="Form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="Form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书名" prop="bookName">
          <el-input v-model="Form.bookName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="借阅日期" prop="borrowDate">
          <el-date-picker v-model="Form.borrowDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item style="padding-left: 10px" label="归还日期" prop="returnDate">
          <el-date-picker v-model="Form.returnDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
#TopMenu {
  height: 60px;
}

.el-menu-demo > .el-menu-item:nth-child(2) {
  margin-left: 100px;
}

.el-menu {
  border-bottom: none !important; /* 移除底部边框 */
}
</style>